<?php
/**
 * 支付宝类
 * Created by PhpStorm.
 * User: smt
 */

namespace extend;
require_once 'alipay-sdk-PHP-4.9.2/AopSdk.php';

class Alipay
{
	
	// 商户配置信息
    public static function getAlipayAppConfig()
    {
        return \config('alipay_app');
    }
    
    /**
     * 单笔转账接口
     * @param $order_number 订单号
     * @param $pay_user_id  收款方user_id
     * @param $amount  转账金额，单位为元，精确到小数点后两位
     * @param $remark   备注
     */
    public static function alipayTransfer($order_number, $pay_user_id, $amount, $remark = '提现')
    {
    	// 我这里打印结果：项目根目录/public/cert/
        // $isdir = getCertRootPath();//证书位置;绝对路径

        // $alipay_conf                  = self::getAlipayAppConfig();
        $aop                          = new \AopCertClient();
        $aop->gatewayUrl              = 'https://openapi.alipay.com/gateway.do';
        $aop->appId                   = '2021002189601389';
        $aop->rsaPrivateKey           = 'MIIEpAIBAAKCAQEAu73O2zF+vjRZ10U03uWGKDhMkznNgj0G0A/iSItPvZTxtKZreUS0mNee5Ey0DcXcGYVxSnpslbpTIKivWMa5Oum0MwwRn4McZzhrlgmAZ1baEHuhxDHl1aTp+k6tvMOUuaFDUB75IzPLP+DF2k4ncL94ItZfNeW6Ifom3Xg2Zx7VMxXzv6aUMp+NZICajJ8M2PVbLW75OWqdIeGDhPoRu2fHeuCdGx626j+4b0kJYT2MFGH1OAfuevVy+ws4mllV6YyWAiCKFwjh63GHXEas+DQwKG4+crLH9oE6ymPWOYSt7a9PbFEvd0VppKXHesOWgOR6t7ZIa9ownOmDpF06FQIDAQABAoIBAC0GHya4HwI0gds7kKtn9h2NKugf86YpRon9VTI6nrwDjVfalWm2zWzeQQ/VSVUIP3mrY/kNlR7vWWI6shqjRebYB0w6t7s+cUBb6olH7BBcZt2PGMN5h/oNm8NYvRfI+9Ds2LzNQMhtcm/2UtzA43qJoKESMjE1z8a4PDveyYU/GM2H0L/l2GCNDeJmv6ou12DLUxFdglvdbkps7/3Xw78siAyPaZ5fIJSOoHIqqbmiXScle4KEUxuJpY6mTlOoSiU7KW6j1Lh6aaI0mMnRrrqRQVDkDottYdxODCHa9LqbhLvVnb6kWQzrVxGpyNXLUOQWuwvDoDdKoQfNcZaCef0CgYEA90zK4TfeZhvF1TxK00sQ35QT4pHvQt+/ROCcj3IUuxxUGK63m5zdkZMNmg35nN2Zzc75UjnHbZjKEjSw/Ez2Jztl+YgJg0ygs+ddpyq3h09dR4x+ekhLdLkqA7rEnGd2YaNeIaklbpLLTttmzIxrdOFqECgSGs7YVNEpKxUsO1cCgYEAwligKCY9OMi5yaB0a9kwdlfo+3A+nP/5ZQ9LM4T/eJ2bPre2CqJit2ausKJhIXyFMLP2RGyr8iMIW2lEq6X35VfA9nShD/CE2FButu3XhcFWSI9W/j249NbCf2XmCXfhhDfGipWDjSQPMJRcZ5iFE0hof0WA1VVLFakVIqmsvnMCgYEA6zaxKPG4qKn1ytFj4gBd9imjmDZxucuS4vI4Nv+s1CMnoapcnLfgzltt7n8oUZk8dtJLtXebRZSzbgmL5Q1Wew41+db4JVg26aZAH4WzthE4iZsJmUk167lKSu3Tn2eQ42E9YQq+vaMFmOV5q0hL1ImqFd/nCHSAsnuWipHC1lUCgYBCNl+aTizdg8WIZBpGBCD2sMy3nW43nx4gyC0eyFkhhtC1dXGX/esUAO/TTf85oWrfRPDKLxwFytm2Cw9SS6FBibw8O1AEVjVsXTrbJ/0dnNkAr5U72VuCTwjEzrqozycOHNKPtJC1LWvfaSxyPwxXnXu8oLlb9Us3ffuta5Fm8QKBgQDNHXlNTEBISw9iJX0GgyPutCwrYD0/p2TKj/r/4+7pLHZOtK071MxLqYN0j06GF7MsHi4swUCCuZIR7Jv+X9XLju8mjAn/pXofZ3DVg347dIQmkhOJmPiTnjFfXL60Zoa6pX7f4qLJ6Dw9ddAJiy0pfLgA9E4hhxsxwvK2xPq1gg=='; // 开发者私钥
        $aop->alipayrsaPublicKey      = '/addons/epay/certs/alipayCertPublicKey.crt';//调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->apiVersion              = '1.0';
        $aop->signType                = 'RSA2';
        $aop->postCharset             = 'utf-8';
        $aop->format                  = 'json';
        $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->appCertSN               = '/addons/epay/certs/appCertPublicKey.crt';//调用getCertSN获取证书序列号
        $aop->alipayRootCertSN        = '/addons/epay/certs/alipayRootCert.crt';//调用getRootCertSN获取支付宝根证书序列号

        $request = new \AlipayFundTransToaccountTransferRequest ();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"" . $order_number . "\"," .
            "\"payee_type\":\"ALIPAY_USERID\"," .
            "\"trade_no\":\"" . $order_number . "\"," .
            "\"payee_account\":\"" . $pay_user_id . "\"," .
            "\"payee_real_name\":\"\"," .
            "\"amount\":\"" . $amount . "\"," .
            "\"remark\":\"" . $remark . "\"" .
            "}");
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode   = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
        	// 成功，返回业务需要的信息
            $data = [
                'code'       => $result->$responseNode->code,
                'msg'        => $result->$responseNode->msg,
                 // 支付宝转账订单号
                'order_id'   => $result->$responseNode->order_id,
                 // 商户订单号
                'out_biz_no' => $result->$responseNode->out_biz_no,
                 // 支付时间
                'pay_date'   => $result->$responseNode->pay_date
            ];
            return $data;
        } else {
        	// 失败记录错误查日志
            self::logs($result, 'alipay_transfer_error');
            return false;
        }
    }



    /**
     * 获取证书根路径
     */
    // public function getCertRootPath() {

    //     return ROOT_PATH.'public/cert/';
    // }

    /**
     * 写日志
     * @param $data : 数据
     * @param $fileName : 写入哪个日志
     */
    public static function logs($data = null, $fileName = null)
    {
        if (is_null($data) || is_null($fileName)) {
            $out_arr['code'] = '400004';
            return $out_arr;
        }

        $path = RUNTIME_PATH . 'log/' . $fileName;

        if (!is_dir($path)) {
            $mkdir_re = mkdir($path, 0777, TRUE);
            if (!$mkdir_re) {
                $this->logs($data, $fileName);
            }
        }

        $filePath = $path . "/" . date("Y-m-d", time());

        $time = date("Y-m-d H:i:s", time());
        $re   = file_put_contents($filePath, $time . " " . var_export($data, TRUE) . "\r\n\r\n", FILE_APPEND);

        if (!$re) {
            $this->logs($data, $fileName);
        } else {
            $out_arr['code'] = '000000';
            return $out_arr;
        }
    }




}



